#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash build.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

create_dir()
{
    local path=$1
    [[ "$path" =~ .*/$ ]] && path=${path%/*}
    if [[ ! -d "$path" && ! -f "$path" ]]; then mkdir -p $path; else path=$path`date "+%y%m%d%H%M%S"` && mkdir -p $path; fi
    echo $path
}

buildpath=$(create_dir $1)       
installpath=$(create_dir $2)

yum install -y m4 environment-modules systemd-devel
yum install -y samtools
source /etc/profile
module purge

set -e
dep_dir="dependency"

bash $dep_dir/bisheng-compiler-2.1.0.sh $buildpath $installpath
module use $installpath/bisheng-compiler-2.1.0
module load $installpath/bisheng-compiler-2.1.0/bisheng_modulefiles


bash $dep_dir/blat-35.1.sh $buildpath $installpath
module use $installpath/blat-35.1
module load $installpath/blat-35.1/blat_modulefiles


bash $dep_dir/bwa-0.7.17.sh $buildpath $installpath 
module use $installpath/bwa-0.7.17
module load  $installpath/bwa-0.7.17/bwa_modulefiles  

bash $dep_dir/bisheng-jdk1.8.0.sh $buildpath $installpath 
module use $installpath/bisheng-jdk1.8.0_322
module load  $installpath/bisheng-jdk1.8.0_322/jdk_modulefiles

bash $dep_dir/gkl-0.8.10.sh $buildpath $installpath

bash gatk-4.0.0.0.sh $buildpath $installpath

mkdir -p pkg/gatk-4.0.0.0-hpc && cp -r $installpath/* pkg/gatk-4.0.0.0-hpc/
cat>"pkg/gatk-4.0.0.0-hpc/run.sh"<<EOF
#!/bin/bash
sudo yum install -y wget tar environment-modules libatomic xz-devel ncurses-devel bzip2-devel curl-devel libpng-devel git cmake automake patch gcc-c++ libtool libatomic zlib-devel libstdc++-static samtools
source /etc/profile &> /dev/null 
current_dir="\$(cd "\$(dirname "\${BASH_SOURCE[0]}")" && pwd -P)"
for f in "\${current_dir}"/*; do
  if [[ -d "\${f}" && -f "\$(ls "\${f}"/*modulefiles 2>&1)" ]]; then
    module use "\${f}" && module load "\${f}"/*modulefiles
  fi
done

basepath=\$(cd \$(dirname "\${BASH_SOURCE[0]}") >/dev/null && pwd)
cd \$basepath/gatk-4.0.0.0
jar uvf ./gatk-package-4.0.0.0-spark.jar com/intel/gkl/*
jar uvf ./gatk-package-4.0.0.0-local.jar com/intel/gkl/*

echo -e "\033[1;32;1mgatk environment initialization completed.\033[0m"
EOF


cd pkg/ && tar zcvf gatk-4.0.0.0-hpc.tar.gz gatk-4.0.0.0-hpc
rm -rf $buildpath $installpath
